package com.hx.setting.action;

import com.hx.setting.action.BaseAction;
import com.hx.setting.action.request.BaseActionRequest;
import com.hx.setting.entity.Entity;
import com.hx.setting.model.Condition;
import com.hx.setting.model.GeneratedCriteria.Term;
import com.hx.setting.model.GeneratedCriteria;
import com.hx.setting.model.Page;
import com.hx.setting.model.TableField;
import com.hx.setting.service.BaseService;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Generate Date : 2014-03-16
 * Generate Version : v3.0
 * Generate Name : Honey v3.1 Test
 * Generate User : THINK
 * JDK Version : 1.5
 */
@SuppressWarnings("rawtypes")
public abstract class GeneralAction extends BaseAction
{

	/** 
	 * 条件参数
	 * 1> 基本查询参数
	 * field:查询字段名称
	 * key/value:字段对应的值
	 * term: 条件(例如: = ,> ,Like等)
	 * 2> fetch查询参数
	 * 参数形式1
	 * fetch={field1:value1,field2:value2,term:like}
	 * fetch={field1:[value1],field2:value2,term:like}
	 * fetch={field1:[value1,value2],term:between}
	 * 参数形式2
	 * fetch=[{field1:value1,field2:value2,term:like},{field1:value1,field2:value2,term:like}]
	 * fetch=[{field1:[value1],field2:value2,term:like}]
	 * fetch=[{field1:[value1,value2],term:between}]
	 * fetch=[参数形式1,参数形式1,参数形式1]
	 * @return
	 */
	protected Condition createCondition()
	{
		Condition answer = null;
		BaseService service = getBaseService();
		HttpServletRequest request = getRequest();
		String sField = request.getParameter( "field" );
		String sFetch = request.getParameter( "fetch" );
		if ( sField != null )
		{
			String value = request.getParameter( "key" );
			if ( value == null || value.length() == 0 )
			{
				value = request.getParameter( "value" );
			}
			String sTerm = request.getParameter( "term" );
			answer = Condition.createDefaultCondition();
			GeneratedCriteria gc = answer.or();
			Term term = Term.getInstance( sTerm );
			if ( value != null && value.length() > 0 )
			{
				String vs[] = value.split( "\n|;|,|\\|" );
				Enum field = (Enum) service.getTableField( sField );
				if ( vs.length == 1 )
				{
					gc.fillCriterion( gc ,term ,field ,vs[0] ,null );
				}
				else
				{
					gc.fillCriterion( gc ,term ,field ,vs[0] ,vs[1] );
				}
			}
			gc = null;
		}
		else if ( sFetch != null )
		{
			char first = sFetch.charAt( 0 );
			if ( first == '{' )
			{
				JSONObject fetch = new JSONObject( new org.json.JSONTokener( sFetch ) );
				if ( fetch.length() > 0 )
				{
					answer = Condition.createDefaultCondition();
					fillFetch( answer.or() ,fetch );
				}
			}
			else if ( first == '[' )
			{
				JSONArray fetch = new JSONArray( new org.json.JSONTokener( sFetch ) );
				Object obj = null;
				answer = Condition.createDefaultCondition();
				GeneratedCriteria gc = answer.or();
				for ( int i = 0, size = fetch.length() ; i < size ; i++ )
				{
					obj = fetch.get( i );
					if ( obj instanceof JSONObject )
					{
						fillFetch( gc ,(JSONObject) obj );
					}
				}
			}
		}
		return answer;
	}

	private final void fillFetch(GeneratedCriteria gc, JSONObject fetch)
	{
		BaseService service = getBaseService();
		String sField = null;
		Object value = null;
		String sTerm = null;
		if ( !fetch.isNull( "term" ) )
		{
			sTerm = fetch.getString( "term" );
			fetch.remove( "term" );
		}
		Term term = Term.getInstance( sTerm );
		Iterator<String> it = fetch.keys();
		while ( it.hasNext() )
		{
			sField = it.next();
			value = fetch.get( sField );
			Enum field = (Enum) service.getTableField( sField );
			if ( value instanceof org.json.JSONArray )
			{
				org.json.JSONArray array = (org.json.JSONArray) value;
				if ( array.length() == 1 )
				{
					gc.fillCriterion( gc ,term ,field ,array.get( 0 ) ,null );
				}
				else if ( array.length() >= 2 )
				{
					gc.fillCriterion( gc ,term ,field ,array.get( 0 ) ,array.get( 1 ) );
				}
			}
			else
			{
				gc.fillCriterion( gc ,term ,field ,value ,null );
			}
		}
	}

	/** 
	 * 创建查询条件
	 * @return
	 * protected Condition createCondition(){
	 * Condition answer = null;
	 * BaseService service = getBaseService();
	 * String field = getParameter("field");
	 * if (field != null) {
	 * String value = getParameter("key");
	 * if(value == null || value.length() == 0 ){
	 * value = getParameter("value");
	 * }
	 * String termStr = getParameter("term");
	 * answer = new Condition(new GeneratedCriteria() {
	 * });
	 * GeneratedCriteria gc = answer.or();
	 * Term term = Term.getInstance(termStr);
	 * if (value != null && value.length() > 0) {
	 * String vs[] = value.split("\n|;|,|\\|");
	 * Enum f = (Enum) service.getTableField(field);
	 * if (vs.length == 1) {
	 * if (Term.LIKE == term) {
	 * gc.andLike(f, value);
	 * } else if (Term.NOT_LIKE == term) {
	 * gc.andNotLike(f, value);
	 * } else {
	 * // >
	 * // >=
	 * // <
	 * // <=
	 * // <>
	 * // !=
	 * //
	 * gc.addCriterion(f, term, value);
	 * }
	 * } else if (vs.length == 2) {
	 * // between
	 * gc.addCriterion(f, term, vs[0], vs[1]);
	 * }
	 * } else {
	 * // is null
	 * // is not null
	 * //
	 * gc.addCriterion((Enum) service.getTableField(field), term);
	 * }
	 * }
	 * return answer;
	 * }
	 * 创建分页对象
	 * @return
	 */
	protected Page createPage()
	{
		BaseService service = getBaseService();
		BaseActionRequest actionRequest = getActionRequest();
		Page answer = new Page( actionRequest.getStart(), actionRequest.getLimit(), actionRequest.getTotal() );
		TableField tf = service.getTableField( actionRequest.getSort() );
		if ( tf != null )
		{
			answer.setOrderBy( tf.toString() ,actionRequest.getDir() );
		}
		return answer;
	}

	/** 
	 * 查询列表
	 */
	public void select()
	{
		try
		{
			BaseService service = getBaseService();
			Page page = createPage();
			String pk = getParameter( "pk" );
			if ( pk == null || pk.length() == 0 )
			{
				List list = null;
				Condition condition = createCondition();
				if ( condition != null )
				{
					if ( service.isSupportAssociationQuery() )
					{
						list = service.selectByDynamicForAssociation( condition ,page );
					}
					else
					{
						list = service.selectByDynamic( condition ,page );
					}
				}
				else
				{
					if ( service.isSupportAssociationQuery() )
					{
						list = service.selectAllForAssociation( page );
					}
					else
					{
						list = service.selectAll( page );
					}
				}
				outList( list ,page );
			}
			else
			{
				Entity entity = null;
				if ( service.isSupportAssociationQuery() )
				{
					entity = service.selectByPrimaryKeyForAssociation( Long.parseLong( pk ) );
				}
				else
				{
					entity = service.selectByPrimaryKey( Long.parseLong( pk ) );
				}
				outEntity( entity );
			}
		}
		catch ( Exception e )
		{
			e.printStackTrace();
			outFail( e.getMessage() );
		}
	}

	/** 
	 * 插入数据
	 */
	public void insert()
	{
		try
		{
			BaseService service = getBaseService();
			BaseActionRequest r = getActionRequest();
			service.insertSelective( r.cloneEntity() );
			outSuccess();
		}
		catch ( Exception e )
		{
			e.printStackTrace();
			outFail( e.getMessage() );
		}
	}

	/** 
	 * 获取详细请(按照主键查询)
	 */
	public void detail()
	{
		try
		{
			String id = getParameter( "id" );
			BaseService service = getBaseService();
			Entity entity = service.selectByPrimaryKey( id );
			outEntity( entity );
		}
		catch ( Exception e )
		{
			e.printStackTrace();
			outFail( e.getMessage() );
		}
	}

	/** 
	 * 修改
	 */
	public void update()
	{
		try
		{
			BaseService service = getBaseService();
			BaseActionRequest request = getActionRequest();
			Entity entity = request.cloneEntity();
			int result = -1;
			if ( entity.getId() == null )
			{
				Condition condition = createCondition();
				result = service.updateByDynamicSelective( condition ,entity );
			}
			else
			{
				result = service.updateByPrimaryKeySelective( entity );
			}
			outSuccess();
		}
		catch ( Exception e )
		{
			e.printStackTrace();
			outFail( e.getMessage() );
		}
	}

	public void delete()
	{
		try
		{
			BaseService service = getBaseService();
			BaseActionRequest r = getActionRequest();
			Condition condition = createCondition();
			int count = 0;
			if ( condition != null )
			{
				count = service.deleteByDynamic( condition );
			}
			outSuccess();
		}
		catch ( Exception e )
		{
			e.printStackTrace();
			outFail( e.getMessage() );
		}
	}

	protected abstract BaseService getBaseService();
}
/* Honey v3.1 Test - version:1 - OriginalChecksum:Bb7d15a13d8f912b9a04736932afb04f8 (do not edit this line) */
